package server

import (
	"context"
	"math/rand"
	"net/http"
	"time"
	__ "user_server/basic/proto"
	"user_server/global"
	"user_server/handler/dao"
	"user_server/handler/model"
)

// server is used to implement helloworld.GreeterServer.
type UserServer struct {
	__.UnimplementedUserServer
}

func (s *UserServer) SendSms(_ context.Context, in *__.SmsSendReq) (*__.SmsSendResp, error) {
	code := rand.Intn(9000) + 1000
	//sms, _ := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	//if *sms.Body.Code != "OK" {
	//	return &__.SmsSendResp{}, errors.New(*sms.Body.Code)
	//}
	global.Rdb.Set(context.Background(), "sendSms"+in.Mobile+in.Source, code, time.Minute*5)
	return &__.SmsSendResp{
		Message: "ok",
		Code:    http.StatusOK,
	}, nil
}

// 注册账号
// SayHello implements helloworld.GreeterServer
func (s *UserServer) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {
	//get := config.Rdb.Get(context.Background(), "sendSms"+in.Mobile+"register")
	//if get.Val() != in.SmsCode {
	//	return &__.RegisterResp{
	//		Message: "短信验证码错误，请重新查证",
	//		Code:    http.StatusBadRequest,
	//	}, nil
	//}
	user := model.User{
		Mobile: in.Mobile,
	}
	if !dao.Create(&user) {
		return &__.RegisterResp{
			Message: "注册错误",
			Code:    http.StatusBadRequest,
		}, nil
	}
	return &__.RegisterResp{
		Message: "ok",
		Code:    http.StatusOK,
	}, nil
}

func (s *UserServer) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	//get := global.Rdb.Get(context.Background(), "sendSms"+in.Mobile+"register")
	//if get.Val() != in.SmsCode {
	//	return &__.LoginResp{
	//		Message: "短信验证码错误，请重新查证",
	//		Code:    http.StatusBadRequest,
	//	}, nil
	//}
	var user model.User
	if !dao.GetOneByFields(&model.User{Mobile: in.Mobile}, &user) {
		return &__.LoginResp{
			Message: "没有查询到此用户账号，请重新查证",
			Code:    http.StatusBadRequest,
		}, nil
	}

	return &__.LoginResp{
		Message: "ok",
		Code:    http.StatusOK,
	}, nil
}

func (s *UserServer) CreateVideo(_ context.Context, in *__.CreateVideoReq) (*__.CreateVideoResp, error) {

	video := model.Video{
		Title:  in.Title,
		Info:   in.Info,
		Video:  in.Video,
		UserId: in.UserId,
		Status: in.Status,
	}
	dao.GetOneByFields(&model.Video{}, &video)
	if video.Id != 0 {
		return &__.CreateVideoResp{
			Message: "此条视频已重复存在",
			Code:    http.StatusOK,
		}, nil
	}
	
	if !dao.Create(&video) {
		return &__.CreateVideoResp{
			Message: "视频上传失败",
			Code:    http.StatusBadRequest,
		}, nil
	}

	return &__.CreateVideoResp{
		Message: "ok",
		Code:    http.StatusOK,
	}, nil
}

func (s *UserServer) FindVideo(_ context.Context, in *__.FindVideoReq) (*__.FindVideoResp, error) {
	var video []model.Video
	dao.GetListByFields(&model.Video{}, &video)
	var videos []*model.Video
	for _, v := range video {
		videos = append(videos, &model.Video{
			Title:  v.Title,
			Info:   v.Info,
			Video:  v.Video,
			UserId: v.UserId,
			Status: v.Status,
		})
	}
	return &__.FindVideoResp{
		Message: "ok",
		Code:    http.StatusOK,
	}, nil
}
